package myrecyclerview

import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

/**
 * @dsc     简介
 * @Author  LiWeiZhong
 * @Date    2025/6/5 18:35
 * @Version 1.0
 */
class RecyclerViewBehavior(context: Context, attrs: AttributeSet): CoordinatorLayout.Behavior<RecyclerView>(
    context, attrs
) {

    private var totalOffset = 0f
    private val maxOffset = 200f
    private val baseDamping = 0.5f

    override fun onStartNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: RecyclerView,
        directTargetChild: View,
        target: View,
        axes: Int,
        type: Int
    ): Boolean {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL
    }

    override fun onNestedPreScroll(
        coordinatorLayout: CoordinatorLayout,
        child: RecyclerView,
        target: View,
        dx: Int,
        dy: Int,
        consumed: IntArray,
        type: Int
    ) {
        if (type == ViewCompat.TYPE_TOUCH) {
            if ((dy < 0 && !child.canScrollVertically(-1)) || (dy > 0 && !child.canScrollVertically(1))) {
                // 计算动态阻尼值（越拉越重）
                val ratio = (abs(totalOffset) / maxOffset).coerceAtMost(1f)
                val damping = baseDamping * (1 - ratio) // 越往下 damping 越小

                val offset = dy * damping
                totalOffset -= offset
                child.translationY = totalOffset
                consumed[1] = dy // 拦截这次滑动
            }
        }
    }

    override fun onNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: RecyclerView,
        target: View,
        dxConsumed: Int,
        dyConsumed: Int,
        dxUnconsumed: Int,
        dyUnconsumed: Int,
        type: Int,
        consumed: IntArray
    ) {
        if (type == ViewCompat.TYPE_NON_TOUCH) {
            if ((dyUnconsumed < 0 && !child.canScrollVertically(-1)) || (dyUnconsumed > 0 && !child.canScrollVertically(1)) ) {
                totalOffset = if (dyUnconsumed < 0) {
                    (child.translationY - dyUnconsumed * 10f).coerceIn(0f, 200f)
                } else {
                    (child.translationY - dyUnconsumed * 10f).coerceIn(-200f, 0f)
                }
                child.translationY = totalOffset
            }
        }
    }

    override fun onStopNestedScroll(
        coordinatorLayout: CoordinatorLayout,
        child: RecyclerView,
        target: View,
        type: Int
    ) {
        if (totalOffset != 0f) {
            child.clearAnimation()
            child.stopScroll()
            // 用户松手，触发回弹动画
            child.animate()
                .translationY(0f)
                .setDuration(300)
                .withEndAction {
                    totalOffset = 0f
                }
                .start()
        }
    }
}